<?php 

$app->post('/login', function() use ($app) {
    $email = $app->request->post('email');
    $password = hash('sha512', $app->request->post('password'));
    if(!validateLogin($email, $password)) {
        $app->flash('error', 'Action failed. Incorrect or missing input.');
        $app->redirect('login');
    }
    $user = Users::whereRaw('user_email = ? AND user_password = ?', array($email, $password))->get();
    if ($user->count() != 0) {
        $_SESSION['email'] = $email;
        $app->redirect('dashboard');
    } else {
        $app->flash('error', 'Login failed');
        $app->redirect('login');
    }
})->name('post-login');

$app->post('/newuser', function() use ($app) {
    $email = $app->request->post('email');
    $password = hash('sha512', $app->request->post('password'));
    if(!validateLogin($email, $password)) {
        $app->flash('error', 'Action failed. Incorrect or missing input.');
        $app->redirect('signup');
    }
    Users::insert(array('user_email' => $email, 'user_password' => $password));
    if(!isset($_SESSION)){
        session_start();
    }
    $_SESSION['email'] = $email;
    $app->redirect('dashboard');
})->name('new-user');

$app->get('/logout', function() use ($app) {
    if(!isset($_SESSION)){
        session_start();
    }
    unset($_SESSION['email']);
    destroySession();
    $app->redirect('login');
})->name('logout');

$app->get('/login', function () use ($app) {
    if(isset($_SESSION['email'])){
        $app->redirect('dashboard');
    }
    $flash = $app->view()->get('flash');
    $error = isset($flash['error']) ? $flash['error'] : '';
    $app->render('login.html.twig', array(
        'pagename' => 'Login',
        'error' => $error
    ));
})->name('login');

$app->get('/signup', function() use ($app) {
    $app->render('signup.html.twig', array(
        'pagename' => 'Signup'
    ));
})->name('signup');